package com.zb.emq;

import com.zb.config.EmqConfig;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class EmqClient {
    @Autowired
    private EmqConfig emqConfig;

    private MqttClient mqttClient;

    @Autowired
    private EmqMessageProccess emqMessageProccess;

    /**
     * 建立连接
     */
    public void connect(){
        try {
            //创建客户端对象
            mqttClient = new MqttClient(emqConfig.getMqttServerUrl(),"web-server-"+ UUID.randomUUID().toString());
            //与服务器建立连接
            mqttClient.connect();
            mqttClient.setCallback(emqMessageProccess);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发布信息
     * @param topic
     * @param msg
     */
    public void publish(String topic,String msg){
        MqttMessage mqttMessage =new MqttMessage(msg.getBytes());
        try {
            mqttClient.getTopic(topic).publish(mqttMessage);
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }

    /**
     * 订阅主题
     * @param topic
     */
    public void subscribe(String topic){
        try {
            mqttClient.subscribe(topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}
